package com.sc.admin.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sc.admin.pojo.Menu;
import com.sc.admin.service.MenuService;
import com.sc.admin.utils.EasyuiTreeNode;

@Controller
public class MainController {
	@Autowired
	private MenuService menuService;
	
	@RequestMapping("/main")
	public String main() {
		return "main";
	}
	
	@RequestMapping("/main/tree")
	public @ResponseBody List<EasyuiTreeNode> tree(@RequestParam(defaultValue="0") int id) {
		List<Menu> menus = menuService.getMenusByPid(id);
		List<EasyuiTreeNode>  nodes = new ArrayList<EasyuiTreeNode>();
		for(Menu m : menus) {
			nodes.add(menuToNode(m));
		}
		return nodes;
	}
	
	private EasyuiTreeNode menuToNode(Menu menu) {
		EasyuiTreeNode node = new EasyuiTreeNode();
		node.setId(menu.getId());
		node.setText(menu.getName());
		node.setState(menu.getIsParent()?"closed":"open");
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("url", menu.getUrl());
		node.setAttributes(attributes);
		return node;
	}
}
